// DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    initializeLogin();
});

// 初始化登录页面
function initializeLogin() {
    setupEventListeners();
    setupPasswordToggle();
}

// 设置事件监听器
function setupEventListeners() {
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    loginForm.addEventListener('submit', handleLogin);
    
    // 注册链接点击
    const registerLink = document.getElementById('registerLink');
    registerLink.addEventListener('click', function(e) {
        e.preventDefault();
        showNotification('注册功能暂未开放', 'info');
    });
}

// 设置密码显示/隐藏切换
function setupPasswordToggle() {
    const togglePassword = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('password');
    
    togglePassword.addEventListener('click', function() {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        
        const icon = this.querySelector('i');
        if (type === 'text') {
            icon.className = 'fas fa-eye-slash';
        } else {
            icon.className = 'fas fa-eye';
        }
    });
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;
    const rememberMe = document.getElementById('rememberMe').checked;
    
    // 验证输入
    if (!username || !password) {
        showNotification('请填写用户名和密码', 'error');
        return;
    }
    
    // 显示加载状态
    showLoading(true);
    
    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                'username': username,
                'password': password,
                'remember_me': rememberMe
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 保存token到localStorage
            localStorage.setItem('access_token', result.access_token);
            localStorage.setItem('username', result.username);
            localStorage.setItem('is_admin', result.is_admin);
            
            if (rememberMe) {
                localStorage.setItem('remember_me', 'true');
            } else {
                localStorage.removeItem('remember_me');
            }
            
            showNotification('登录成功！正在跳转...', 'success');
            
            // 延迟跳转，让用户看到成功消息
            setTimeout(() => {
                window.location.href = '/dashboard';
            }, 1000);
        } else {
            showNotification(result.message || '登录失败', 'error');
        }
    } catch (error) {
        console.error('登录失败:', error);
        showNotification('登录失败，请检查网络连接', 'error');
    } finally {
        showLoading(false);
    }
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (show) {
        loadingOverlay.classList.remove('hidden');
    } else {
        loadingOverlay.classList.add('hidden');
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full`;
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            notification.className += ' bg-green-500 text-white';
            break;
        case 'error':
            notification.className += ' bg-red-500 text-white';
            break;
        case 'warning':
            notification.className += ' bg-yellow-500 text-white';
            break;
        default:
            notification.className += ' bg-blue-500 text-white';
    }
    
    notification.innerHTML = `
        <div class="flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 检查是否已登录
function checkLoginStatus() {
    const token = localStorage.getItem('access_token');
    if (token) {
        // 验证token是否有效
        fetch('/api/verify-token', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.valid) {
                // 如果已登录且token有效，直接跳转到主页
                window.location.href = '/dashboard';
            } else {
                // token无效，清除本地存储
                localStorage.removeItem('access_token');
                localStorage.removeItem('username');
            }
        })
        .catch(() => {
            // 网络错误，清除本地存储
            localStorage.removeItem('access_token');
            localStorage.removeItem('username');
        });
    }
}

// 页面加载时检查登录状态
checkLoginStatus(); 